/*
 * @Author: 玩家
 * @Date: 2020-05-21 10:32:02
 * @LastEditTime: 2020-05-26 11:27:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jump\assets\script\game\stage\Player.ts
 */

const {ccclass, property} = cc._decorator;

@ccclass
export class Player extends cc.Component {

    @property(cc.Float)
    public jumpDistance: number = 0;
    @property(cc.Integer)
    public power: number = 0;
    @property(cc.Float)
    public initSpeed: number = 0;

    public speed: number = 0;
    public isReadJump: boolean = false;
    public direction: number = 1;

    @property({
        type: cc.AudioClip,
    })
    private readyJumpAudio = null;
    private readyJumpAudioId = -1;
    @property({
        type: cc.AudioClip,
    })
    private jumpAudio = null;
    private jumpAudioId = -1;

    public readyJump() {
        this.readyJumpAudioId = cc.audioEngine.play(this.readyJumpAudio, false, 1);
        // 模拟弹簧压缩效果
        cc.tween(cc.find("rotateAnchor/sprite", this.node))
            .then(cc.scaleTo(2, 1, 0.5))
            .start();
        this.speed = this.initSpeed;
        this.isReadJump = true;
    }

    public jumpTo(worldPos: cc.Vec2, cb: Function, cbTarget?:any) {
        // 停止跳跃前的 音乐、动作  播放跳跃音乐
        cc.audioEngine.stop(this.readyJumpAudioId);
        this.jumpAudioId = cc.audioEngine.play(this.jumpAudio, false, 1);
        cc.find("rotateAnchor/sprite", this.node).stopAllActions();

        let targetPos = this.node.parent.convertToNodeSpaceAR(worldPos);
        this.isReadJump =false;

        // 弹簧压缩效果
        cc.tween(cc.find("rotateAnchor/sprite", this.node))
            .to(1, {scale: 1})
            .start();

        // 旋转效果
        cc.tween(cc.find("rotateAnchor", this.node))
            .by(0.5, {angle: this.direction * 360})
            .start();

        // 跳跃效果
        cc.tween(this.node)
            .then(cc.jumpTo(0.5, targetPos, 200, 1))
            .call(()=>{
                // 动作结束后，随机生成左右方向
                this.direction = Math.random() > 0.5 ? 1 : -1;
                this.speed = 0;
                this.jumpDistance = 0;
                // 执行传入函数
                cb();
            }).start();
    }

    // 蓄力跳跃
    update(dt) {
        if (this.isReadJump) {
            this.speed += dt * this.power;
            this.jumpDistance += this.speed * dt;
        }
    }
}